package com.yylending.las.common.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import com.yyfax.common.CLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 仿CEIS升级, 提取出来的.
 *
 * Created by ying_he on 2017/5/3.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public final class StorageUtils {
	private static final String TAG = "StorageUtils";
	private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";
	private static final String INDIVIDUAL_DIR_NAME = "uil-images";
	public static final String SCREENSHOTS_DIR_NAME = "screenShots";
	public static final String SCREENSHOT_FILE_NAME_TEMPLATE = "Screenshot.jpg";
	public static final String SCREENSHOT_FILE_PATH_TEMPLATE = "%s/%s/%s";

    private StorageUtils() {
    }

    public static File getCacheDirectory(Context context) {
        return getCacheDirectory(context, true);
    }

    public static File getCacheDirectory(Context context, boolean preferExternal) {
        File appCacheDir = null;

        String externalStorageState;
        try {
            externalStorageState = Environment.getExternalStorageState();
        } catch (NullPointerException var5) {
            externalStorageState = "";
        }

        if(preferExternal && "mounted".equals(externalStorageState) && hasExternalStoragePermission(context)) {
            appCacheDir = getExternalCacheDir(context);
        }

        if(appCacheDir == null) {
            appCacheDir = context.getCacheDir();
        }

        if(appCacheDir == null) {
            String cacheDirPath = "/data/data/" + context.getPackageName() + "/cache/";
            appCacheDir = new File(cacheDirPath);
        }

        return appCacheDir;
    }

    public static File getIndividualCacheDirectory(Context context) {
        return getIndividualCacheDirectory(context, "uil-images");
    }

    public static File getIndividualCacheDirectory(Context context, String cacheDir) {
        File appCacheDir = getCacheDirectory(context);
        File individualCacheDir = new File(appCacheDir, cacheDir);
        if(!individualCacheDir.exists() && !individualCacheDir.mkdir()) {
            individualCacheDir = appCacheDir;
        }

        return individualCacheDir;
    }

    public static File getOwnCacheDirectory(Context context, String cacheDir) {
        File appCacheDir = null;
        if("mounted".equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
            appCacheDir = new File(Environment.getExternalStorageDirectory(), cacheDir);
        }

        if(appCacheDir == null || !appCacheDir.exists() && !appCacheDir.mkdirs()) {
            appCacheDir = context.getCacheDir();
        }

        return appCacheDir;
    }

    public static File getOwnCacheDirectory(Context context, String cacheDir, boolean preferExternal) {
        File appCacheDir = null;
        if(preferExternal && "mounted".equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
            appCacheDir = new File(Environment.getExternalStorageDirectory(), cacheDir);
        }

        if(appCacheDir == null || !appCacheDir.exists() && !appCacheDir.mkdirs()) {
            appCacheDir = context.getCacheDir();
        }

        return appCacheDir;
    }

    private static File getExternalCacheDir(Context context) {
        File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
        File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
        if(!appCacheDir.exists()) {
            if(!appCacheDir.mkdirs()) {
                return null;
            }

            try {
                (new File(appCacheDir, ".nomedia")).createNewFile();
            } catch (IOException var4) {
            }
        }

        return appCacheDir;
    }

	private static boolean hasExternalStoragePermission(Context context) {
		int perm = context.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE");
		return perm == 0;
	}

	/**
	 * 存储到sdcard * * @param bmp * @return
	 */
	public static String saveToSD(Bitmap bmp) {
		//判断sd卡是否存在
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			//文件全名
			String mRootPath = Environment.getExternalStorageDirectory().toString();
			CLog.i(TAG, "mRootPath:" + mRootPath);
			File rootFile = new File(mRootPath + "/" + SCREENSHOTS_DIR_NAME);
			if(!rootFile.exists()){
				rootFile.mkdirs();
			}
			String mFilePath = String.format(SCREENSHOT_FILE_PATH_TEMPLATE, mRootPath, SCREENSHOTS_DIR_NAME, SCREENSHOT_FILE_NAME_TEMPLATE);
			CLog.i(TAG, "file path:" + mFilePath);
			File file = new File(mFilePath);
			if (file.exists()) {
				file.delete();
			}
			try {
				file.createNewFile();
				CLog.i(TAG, "file path:" + file.getAbsolutePath());
				FileOutputStream fos = null;
				fos = new FileOutputStream(file);
				if (fos != null) {
					//第一参数是图片格式，第二参数是图片质量，第三参数是输出流
					bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
					fos.flush();
				}
				if (fos != null) {
					fos.close();
				}
				return mFilePath;
			} catch (IOException e) {
				CLog.i(TAG, "file path:" + file.getAbsolutePath());
			}
		}
		return null;
	}

	/**
	 * 删除文件
	 */
	public static boolean deleteFile(String filePath) {
		//判断sd卡是否存在
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File file = new File(filePath);
			if (file.exists()) {
				file.delete();
			}
			return true;
		}
		return false;
	}
}
